package ch.subgate.spritestudio;

import java.util.ArrayList;

import ch.subgate.spritestudio.constants.Constants;
import ch.subgate.spritestudio.tools.DataManager;
import ch.subgate.spritestudio.tools.SpritesAdapter;
import ch.subgate.spritestudio.types.Sprite;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Typeface;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

public class MainMenuActivity extends Activity implements OnItemClickListener, MediaScannerConnection.MediaScannerConnectionClient {
	
	private String mProjectName;
	
	private ArrayList<Sprite> mSprites;
	
	private MediaScannerConnection mMediaScanner;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.mainmenu_layout);
		
		mProjectName = Constants.DEFAULT_PROJECT_DIR;
		
		// Set up media scanner and initiate connection
		mMediaScanner = new MediaScannerConnection(this, this);
		mMediaScanner.connect();
		
		mSprites = new ArrayList<Sprite>();
		// Add placeholder
		mSprites.add(new Sprite(null, null));
		DataManager.loadProjectSprites(
				mSprites,
				mProjectName,
				true);
		Toast.makeText(
				getApplicationContext(),
				(mSprites.size() - 1) + " sprites loaded.",
				Toast.LENGTH_SHORT).show();
		
		GridView gridView = (GridView)findViewById(R.id.spritegrid);
		gridView.setAdapter(new SpritesAdapter(
				getApplicationContext(),
				mSprites));
		gridView.setOnItemClickListener(this);
		
		TextView textView = (TextView)findViewById(R.id.projecttitle);
		textView.setText(Constants.DEFAULT_PROJECT_DIR);
		
		Typeface face = Typeface.createFromAsset(
				getAssets(),
				"fonts/Roboto-Thin.ttf");
		textView.setTypeface(face);
		
		// Preparing grid view for context menu
		registerForContextMenu(gridView);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
	}
	
	@Override
	protected void onDestroy() {
		if (mSprites != null) {
			for (Sprite sprite : mSprites) {
				sprite.recycle();
			}
			mSprites.clear();
		}
		mMediaScanner.disconnect();
		mMediaScanner = null;
		super.onDestroy();
	}
	
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.spritecontext_menu, menu);
	}
	
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
		if (info.position > 0) {
			GridView gridView = (GridView)findViewById(R.id.spritegrid);
			SpritesAdapter adapter = (SpritesAdapter)gridView.getAdapter();
			switch (item.getItemId()) {
			case R.id.deletesprite:
				Sprite sprite = mSprites.get(info.position);
				mSprites.remove(info.position);
				DataManager.deleteSprite(sprite);
				sprite = null;
				adapter.notifyDataSetChanged();
				break;
			}
		}
		else {
			Toast.makeText(
					this,
					"Not applicable for this item.",
					Toast.LENGTH_SHORT).show();
		}
		return true;
	}
	
	/** Method is invoked when an item from gridview recieves a click */
	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		if (position > 0) {
			String fileName = mSprites.get(position).mFileName;
			String projectName = mSprites.get(position).mProjectName;
			
			Intent intent = new Intent(
					MainMenuActivity.this,
					PainterActivity.class);
			intent.putExtra("filename", fileName);
			intent.putExtra("projectname", projectName);
			intent.putExtra("newfile", false);
			intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
			startActivityForResult(intent, 0);
		}
		else if (position == 0) {
			showDialog(Constants.DIALOG_NEWPICTURE_ID);
		}
	}
	
	@Override
	protected void onActivityResult(
			int requestCode,
			int resultCode,
			Intent data) {
		if (resultCode == RESULT_OK) {
			String filePath = data.getStringExtra("filepath");
			boolean updated = data.getBooleanExtra("fileupdated", false);
			
			if (updated && mMediaScanner.isConnected()) {
				mMediaScanner.scanFile(filePath, null);
			}
		}
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		final Dialog dialog = new Dialog(this);
		
		switch (id) {
		case Constants.DIALOG_NEWPICTURE_ID:
			// Set up dialog
			dialog.setContentView(R.layout.newpicture_layout);
			dialog.setTitle(R.string.newpicturedialog_titletext);
			// Set listeners for dialog
			Button okButton = (Button)dialog.findViewById(R.id.newpicturedialog_okbutton);
			okButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View view) {
					EditText editText = (EditText)dialog.findViewById(R.id.newpicturedialog_filename);
					String fileName = editText.getText().toString();
					
					int width;
					int height;
					try {
						editText = (EditText)dialog.findViewById(R.id.newpicturedialog_wedittext);
						width = Integer.parseInt(editText.getText().toString());
						editText = (EditText)dialog.findViewById(R.id.newpicturedialog_hedittext);
						height = Integer.parseInt(editText.getText().toString());
					}
					catch (NumberFormatException e) {
						width = 0;
						height = 0;
					}
					
					if (
							fileName.length() > 0
							&& width > 0
							&& height > 0
							&& Sprite.isValidFileName(fileName)) {
						dialog.dismiss();
						
						if (width * height > 1024 * 1024) {
							Toast.makeText(
									MainMenuActivity.this,
									"Warning: This picture size may cause your device to crash",
									Toast.LENGTH_LONG).show();
						}
						
						Intent intent = new Intent(
								MainMenuActivity.this,
								PainterActivity.class);
						intent.putExtra("filename", fileName);
						intent.putExtra("projectname", Constants.DEFAULT_PROJECT_DIR);
						intent.putExtra("width", width);
						intent.putExtra("height", height);
						intent.putExtra("newfile", true);
						intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
						startActivity(intent);
					}
					else {
						Toast.makeText(
								MainMenuActivity.this,
								"Entered properties are invalid.",
								Toast.LENGTH_SHORT).show();
					}
				}
			});
			
			Button cancelButton = (Button)dialog.findViewById(R.id.newpicturedialog_cancelbutton);
			cancelButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View view) {
					dialog.dismiss();
				}
			});
			break;
		}
		return dialog;
	}

	@Override
	public void onMediaScannerConnected() {
		// TODO nothing
	}
	
	@Override
	public void onScanCompleted(String path, Uri uri) {
		// TODO nothing
	}
}
